package com.aop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.aop.domain.entity.OperationLog;
import com.aop.mapper.OperationLogMapper;
import com.aop.service.IOperationLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.dto.OperationLogDTO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2025-10-11
 */
@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements IOperationLogService {
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public void saveLog(OperationLogDTO operationLog) {
        OperationLog properties = BeanUtil.copyProperties(operationLog, OperationLog.class);
        save(properties);
    }

    @Override
    public IPage<OperationLog> getLogList(
            String userName,
            String operationType,
            String operationModule,
            String status,
            String startTime,
            String endTime,
            Integer pageNum,
            Integer pageSize
    ) {
        // 构建分页对象
        Page<OperationLog> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        
        // 用户名模糊查询
        wrapper.like(StrUtil.isNotBlank(userName), OperationLog::getUserName, userName);
        
        // 操作类型精确匹配
        wrapper.eq(StrUtil.isNotBlank(operationType), OperationLog::getOperationType, operationType);
        
        // 操作模块精确匹配
        wrapper.eq(StrUtil.isNotBlank(operationModule), OperationLog::getOperationModule, operationModule);
        
        // 操作状态精确匹配
        wrapper.eq(StrUtil.isNotBlank(status), OperationLog::getStatus, status);
        
        // 操作时间范围查询
        if (StrUtil.isNotBlank(startTime)) {
            LocalDateTime startDateTime = LocalDateTime.parse(startTime + " 00:00:00", DATE_FORMATTER);
            wrapper.ge(OperationLog::getOperationTime, startDateTime);
        }
        
        if (StrUtil.isNotBlank(endTime)) {
            LocalDateTime endDateTime = LocalDateTime.parse(endTime + " 23:59:59", DATE_FORMATTER);
            wrapper.le(OperationLog::getOperationTime, endDateTime);
        }
        
        // 按操作时间倒序排列
        wrapper.orderByDesc(OperationLog::getOperationTime);
        
        // 执行分页查询
        return page(page, wrapper);
    }
}
